<template>
  <view class="page-wrapper">
    <!-- 搜索框 -->
    <view class="search-container" :style="{ height: statusBarHeight + 'px' }">
      <view class="search-box">
        <span style="text-align: center; flex: 1; color: #fff">店铺端首页</span>
      </view>
    </view>

    <!-- 页面主体内容 -->
    <view class="store-container">
      <!-- 头部轮播图 -->
      <view class="swiper-section">
        <swiper
          class="swiper"
          indicator-dots
          autoplay
          circular
          indicator-active-color="#1989fa"
          indicator-color="rgba(255,255,255,0.5)"
        >
          <swiper-item
            v-for="(item, index) in homeInfo.bannerList"
            :key="index"
            class="swiper-item"
          >
            <image
              :src="item.ad_image"
              class="banner-image"
              mode="fill"
            ></image>
          </swiper-item>
        </swiper>
      </view>

      <!-- 供应商区域 -->
      <view class="section">
        <view class="section-header">
          <text class="section-title">附近供应商</text>
          <view class="view-all" @click="toAroundSupplier">
            <text class="view-all-text">查看全部</text>
            <text class="gui-icons gui-block gui-text arrow-icon"
              >&#xe601;</text
            >
          </view>
        </view>
        <view class="suppliers-grid">
          <view
            class="supplier-item"
            v-for="(item, index) in homeInfo.supplierList"
            @click="toSupplierDetail(item.id)"
            :key="index"
          >
            <image :src="item.logo" class="supplier-logo" mode="fill"></image>
            <text class="supplier-name">{{ item.name }}</text>
            <text class="supplier-distance"
              >{{ (item.distance / 1000).toFixed(2) }}km</text
            >
          </view>
        </view>
      </view>

      <!-- 品牌区域 -->
      <view class="section">
        <view class="section-header">
          <text class="section-title">精选品牌</text>
          <view class="view-all" @click="toBrandList">
            <text class="view-all-text">查看更多</text>
            <text class="gui-icons gui-block gui-text arrow-icon"
              >&#xe601;</text
            >
          </view>
        </view>
        <view class="brands-grid">
          <view
            class="brand-item"
            v-for="(item, index) in homeInfo.brandList"
            :key="index"
            @click="navigateToBrand(item)"
          >
            <image :src="item.logo_url" class="brand-logo" mode="fill"></image>
            <text class="brand-name">{{ item.name }}</text>
          </view>
        </view>
      </view>

      <!-- 底部自定义tabbar -->
      <custom-tabbar
        :currentIndex="currentTabIndex"
        @tabChange="handleTabChange"
      />
      <!-- 底部占位，防止内容被tabbar遮挡 -->
      <view class="tabbar-placeholder"></view>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import CustomTabbar from "../components/tabbar.vue";
import {
  getBannerList,
  getAroundSupplierList,
  getJXBrandList,
} from "@/apiShop/home";
import { onLoad } from "@dcloudio/uni-app";
import { showToast } from "@/utils/helper";
import customHeader from "@/component/customHeader.vue";
import { getLocationByGaode } from "@/utils/helper";
// 当前选中的标签页索引
const currentTabIndex = ref(0);
const statusBarHeight = ref(
  getApp().globalData.systemInfo.statusBarHeight + 44
);
const homeInfo = ref({
  bannerList: [],
  brandList: [],
  supplierList: [],
});

const loaction = ref({
  latitude: undefined,
  longitude: undefined,
});

const getBannerListData = async () => {
  const res = await getBannerList();
  homeInfo.value.bannerList = res;
};

const getBrandList = async () => {
  const res = await getJXBrandList();
  homeInfo.value.brandList = res.data;
};

// const getSupplierList = async () => {
//   uni.getLocation({
//     type: "gcj02",
//     success: async (res) => {
//       loaction.value.latitude = res.latitude;
//       loaction.value.longitude = res.longitude;
//       const ress = await getAroundSupplierList({
//         user_lat: loaction.value.latitude,
//         user_lng: loaction.value.longitude,
//         limit: 99,
//         page: 1,
//       });
//       homeInfo.value.supplierList = ress.data.filter(
//         (item, index) => index < 3
//       );
//       getApp().globalData.location = {
//         latitude: res.latitude,
//         longitude: res.longitude,
//       };
//     },
//     fail: (err) => {
//       showToast(err);
//     },
//   });
// };

const getSupplierList = async () => {
  // 检查是否已授权位置信息
  uni.getSetting({
    success: (res) => {
      if (res.authSetting["scope.userLocation"]) {
        // 已授权，直接获取位置
        getLocation();
      } else {
        // 未授权，先请求授权
        requestLocationAuth();
      }
    },
  });
};

// 请求位置授权
const requestLocationAuth = () => {
  uni.authorize({
    scope: "scope.userLocation",
    success: () => {
      // 用户同意授权，获取位置
      getLocation();
    },
    fail: () => {
      // 用户拒绝授权，显示提示并打开设置页面
      showAuthModal();
    },
  });
};

// 显示授权提示弹窗
const showAuthModal = () => {
  uni.showModal({
    title: "位置信息授权",
    content:
      "需要获取您的位置信息才能为您提供周边供应商服务，请授权获取位置信息",
    confirmText: "去授权",
    cancelText: "退出应用",
    success: (res) => {
      if (res.confirm) {
        // 打开设置页面让用户手动开启授权
        uni.openSetting({
          success: (settingRes) => {
            if (settingRes.authSetting["scope.userLocation"]) {
              // 用户在设置页面中同意授权
              getLocation();
            } else {
              // 用户仍然拒绝授权，再次提示
              uni.showToast({
                title: "未授权位置信息，无法使用本应用",
                icon: "none",
                duration: 2000,
                complete: () => {
                  setTimeout(() => {
                    showAuthModal(); // 再次显示授权弹窗，形成循环
                  }, 2000);
                },
              });
            }
          },
        });
      } else {
        wx.exitMiniProgram({ success: (res) => {} });
      }
    },
    // 防止用户通过点击遮罩层关闭弹窗
    maskClosable: false,
  });
};

// 获取位置信息
const getLocation = async () => {
  try {
      const { latitude, longitude } = await getLocationByGaode();
      loaction.value.latitude = latitude;
      loaction.value.longitude = longitude;
      const ress = await getAroundSupplierList({
        user_lat: loaction.value.latitude,
        user_lng: loaction.value.longitude,
        limit: 99,
        page: 1,
      });
      homeInfo.value.supplierList = ress.data.filter(
        (item, index) => index < 3
      );
      getApp().globalData.location = {
        latitude: loaction.value.latitude,
        longitude: loaction.value.longitude,
      };
    } catch (err) {
      showAuthModal();
    }
  // uni.getLocation({
  //   type: "gcj02",
  //   success: async (res) => {
  //     loaction.value.latitude = res.latitude;
  //     loaction.value.longitude = res.longitude;
  //     const ress = await getAroundSupplierList({
  //       user_lat: loaction.value.latitude,
  //       user_lng: loaction.value.longitude,
  //       limit: 99,
  //       page: 1,
  //     });
  //     homeInfo.value.supplierList = ress.data.filter(
  //       (item, index) => index < 3
  //     );
  //     getApp().globalData.location = {
  //       latitude: res.latitude,
  //       longitude: res.longitude,
  //     };
  //   },
  //   fail: (err) => {
  //     // 获取位置失败，可能是系统原因，再次尝试授权
  //     showToast(
  //       "获取位置信息失败，请检查手机的GPS定位是否开启,若未开启无法获取位置"
  //     );
  //     setTimeout(() => {
  //       showAuthModal();
  //     }, 2000);
  //   },
  // });
};
onLoad(async () => {
  await getBannerListData();
  await getBrandList();
  await getSupplierList();
});
// 处理标签页切换
const handleTabChange = (index) => {
  currentTabIndex.value = index;
  // 这里可以添加页面跳转逻辑
  switch (index) {
    case 0:
      uni.reLaunch({ url: "/pagesShop/store/storeHome" });
      break;
    case 1:
      uni.reLaunch({ url: "/pagesShop/cate/index" });
      break;
    case 2:
      uni.reLaunch({ url: "/pagesShop/mine/index" });
      break;
  }
};

const toAroundSupplier = () => {
  uni.navigateTo({
    url: `/pagesShop/supplier/aroundSupplier?loaction=${JSON.stringify(
      loaction.value
    )}`,
  });
};

const toSupplierDetail = (id) => {
  uni.navigateTo({
    url: `/pagesShop/supplier/supplierInfo?id=${id}&location=${JSON.stringify(
      loaction.value
    )}`,
  });
};

const toBrandList = () => {
  uni.reLaunch({
    url: `/pagesShop/cate/index`,
  });
};
const navigateToBrand = (brand) => {
  // 实际开发中可以跳转到品牌详情页
  uni.navigateTo({
    url: `/pagesShop/supplier/supplierBrand?id=${brand.id}&brand_name=${brand.name}`,
  });
};
</script>

<style scoped lang="scss">
.page-wrapper {
  min-height: 100vh;
  background: linear-gradient(to bottom, #539df7 10%, #f3f5fa 40%);
  padding-bottom: 100rpx;
}

.search-container {
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.search-box {
  display: flex;
  align-items: center;
  /* background-color: #ffffff; */
  border-radius: 40rpx;
  padding: 10rpx 20rpx;
}

.search-icon {
  color: #999;
  margin-right: 10rpx;
  font-size: 32rpx;
}

.store-container {
  padding: 0 30rpx;
}

/* 轮播图样式 */
.swiper-section {
  width: 100%;
  height: 380rpx;
  border-radius: 24rpx;
  overflow: hidden;
  margin-bottom: 20rpx;
}

.swiper {
  width: 100%;
  height: 100%;
  border-radius: 24rpx;
}

.swiper-item {
  width: 100%;
  height: 100%;
  border-radius: 24rpx;
}

.banner-image {
  width: 100%;
  height: 100%;
  border-radius: 24rpx;
}

/* 分区样式 */
.section {
  margin-top: 20rpx;
  background-color: #ffffff;
  padding: 20rpx;
  border-radius: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
}

.section-title:before {
  content: "";
  display: inline-block;
  width: 8rpx;
  height: 32rpx;
  background-color: #1989fa;
  border-radius: 4rpx;
  margin-right: 10rpx;
}

.view-all {
  display: flex;
  align-items: center;
}

.view-all-text {
  font-size: 26rpx;
  color: #1989fa;
}

.arrow-icon {
  font-size: 26rpx;
  color: #1989fa;
  margin-left: 4rpx;
}

/* 供应商网格 */
.suppliers-grid {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20rpx;
}

.supplier-item {
  width: 33.33%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30rpx;
}

.supplier-logo {
  width: 180rpx;
  height: 180rpx;
  border-radius: 10rpx;
  object-fit: cover;
}

.supplier-name {
  font-size: 26rpx;
  color: #333;
  margin-top: 10rpx;
  text-align: center;
}

.supplier-distance {
  font-size: 24rpx;
  color: #999;
  margin-top: 6rpx;
}

/* 品牌网格 */
.brands-grid {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20rpx;
}

.brand-item {
  width: 33.33%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30rpx;
}

.brand-logo {
  width: 180rpx;
  height: 180rpx;
  border-radius: 10rpx;
  object-fit: cover;
}

.brand-name {
  font-size: 26rpx;
  color: #333;
  margin-top: 10rpx;
  text-align: center;
}

/* 底部占位 */
.tabbar-placeholder {
  height: 100rpx;
}
</style>
